const rechargeService = require('../service/recharge.service')
const userService = require('../service/user.service')
const R = require('../utils/R')
const { RECHARGE_EXCEPTION } = require('../error/errorType')

class RechargeController {
  async recharge (ctx, next) {
    try {
      const { id: userId, name } = ctx.userInfo
      const { amount, status, orderNo } = ctx.orderInfo
      const result = await rechargeService.recharge(amount, orderNo, userId, status)
      if (result.insertId) {
        const [userInfo] = await userService.getUserInfoByName(name)
        await userService.updateAmount(Number(+userInfo.amount) + Number(amount), userId);
        ctx.dto = R.ok('充值成功', {
          userId,
          amount,
          status
        })
      }

    } catch (err) {
      console.log(err.message)
      return ctx.app.emit('error', new Error(RECHARGE_EXCEPTION), ctx)
    }
    await next()
  }
}

module.exports = new RechargeController()